package superminer.xinfang.com.ipreport.util;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * tcp客户端
 * Created by Administrator on 2018/2/26.
 */

public class TcpClientConnector {
    private static TcpClientConnector mTcpClientConnector;
    private Socket mClient;
    private ConnectLinstener mListener;
    private Thread mConnectThread;

    public interface ConnectLinstener {
        void onReceiveData(int code, String data);
    }

    public void setOnConnectLinstener(ConnectLinstener linstener) {
        this.mListener = linstener;
    }

    /**
     * 获得单例对象
     * @return
     */
    public static TcpClientConnector getInstance() {
        if (mTcpClientConnector == null) mTcpClientConnector = new TcpClientConnector();
        return mTcpClientConnector;
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    if (mListener != null) {
                        mListener.onReceiveData(msg.getData().getInt("code"),msg.getData().getString("data"));
                    }
                    break;
            }
        }
    };

    /**
     * 回调连接是否成功
     */
    public interface ConnectResultListener{
       void  setResult(boolean isConnect);
    }

    /**
     * 创建tcp连接
     * @param mSerIP
     * @param mSerPort
     */
    public void creatConnect(final String mSerIP, final int mSerPort, final ConnectResultListener connectResultListener) {

        final Handler myHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                       //连接失败
                        connectResultListener.setResult(false);
                        break;
                    case 1:
                       //连接成功
                        connectResultListener.setResult(true);
                        break;
                }
                super.handleMessage(msg);
            }
        };

        if (mConnectThread!=null)
        {
            //线程释放
            mConnectThread.interrupt();
            mConnectThread=null;
        }
        if (mConnectThread == null) {
            mConnectThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        connect(mSerIP, mSerPort);
//                        Log.i("-->","连接线程");
//                        myHandler.sendEmptyMessage(1);
                    } catch (IOException e) {
                        e.printStackTrace();
                        //连接失败
                        myHandler.sendEmptyMessage(0);
                    }
                }
            });
            mConnectThread.start();
        }
    }

    /**
     * 与服务端进行连接 * * @throws IOException
     */
    private void connect(String mSerIP, int mSerPort) throws IOException {
        if (mClient == null||!mClient.isConnected()) {
            mClient = new Socket(mSerIP, mSerPort);

        }

        InputStream inputStream = mClient.getInputStream();

        byte[] head = new byte[4];
        if (inputStream.read(head)!=-1)
        {
//            int headInt = bytesToInt2(head, 0);

            byte[] code = new byte[1];
            {
                if (inputStream.read(code)!=-1)
                {

                    byte[] buffer = new byte[1024];
                    int len = -1;
                    while ((len = inputStream.read(buffer)) != -1) {
                        String data = new String(buffer, 0, len);
                        Message message = new Message();
                        message.what = 100;
                        Bundle bundle = new Bundle();
                        bundle.putString("data", data);
                        bundle.putInt("code",code[0]);
                        Log.i("-->","code:"+code[0]);
                        message.setData(bundle);
                        mHandler.sendMessage(message);
                    }
                }
            }

        }

    }

    /**
     * 发送数据 * * @param data 需要发送的内容
     */
    public boolean send(int code,String data) throws IOException {
        if (mClient!=null)
        {
            OutputStream outputStream = mClient.getOutputStream();
            byte[] bytes = data.getBytes();

            int head= 0xff<<22|(bytes.length+1);
            byte[] headbyte =IntToBytes.intToBytes2(head);
            byte[]  allByte= new byte[bytes.length+headbyte.length+1];
            Log.i("-->","发送头的长度："+headbyte.length);
            System.arraycopy(headbyte,0,allByte,0,headbyte.length);

            System.arraycopy(new byte[]{(byte) code},0,allByte,headbyte.length,1);
            System.arraycopy(bytes,0,allByte,headbyte.length+1,bytes.length);
            outputStream.write(allByte);
            return true;
        }else
        {
          return false;
        }

    }

    /**
     * 断开连接 * * @throws IOException
     */
    public void disconnect() throws IOException {
        if (mClient != null) {
            mClient.close();
            mClient = null;
        }
    }


    /**
     * 是否连接
     * @return
     */
    public boolean isConnect()
    {
        if (mClient==null)
        {
            Log.i("-->","sokect为空");
            return false;
        }
        return mClient.isConnected();
    }

}
